package br.senai.sc.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.senai.sc.dao.GenericDAOImp;
import br.senai.sc.entity.Imagem;

@WebServlet("/images/*")
public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		GenericDAOImp<?, ?> dao = new GenericDAOImp<>();
		String descricao = String.valueOf(request.getPathInfo().substring(1));
		if (descricao != null) {
			Imagem imagem = (Imagem) dao.listByProperty(Imagem.class,
					"descricao", descricao);
			if (imagem != null) {
				response.setHeader("Content-Type", getServletContext()
						.getMimeType(imagem.getDescricao()));
				response.setHeader("Content-Disposition", "inline; filename=\""
						+ imagem.getDescricao() + "\"");
				BufferedInputStream input = null;
				BufferedOutputStream output = null;
				try {
					input = new BufferedInputStream(new ByteArrayInputStream(
							imagem.getImagem())); // Creates buffered input
													// stream.
					output = new BufferedOutputStream(
							response.getOutputStream());
					byte[] buffer = new byte[8192];
					for (int length = 0; (length = input.read(buffer)) > 0;) {
						output.write(buffer, 0, length);
					}
				} finally {
					if (output != null)
						try {
							output.close();
						} catch (IOException logOrIgnore) {
						}
					if (input != null)
						try {
							input.close();
						} catch (IOException logOrIgnore) {
						}
				}
			}
		}
	}

}
